<?php

namespace Icsoc\UIBundle\Controller;

use Doctrine\ORM\NoResultException;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Icsoc\UIBundle\Entity\Intro;
use Icsoc\UIBundle\Entity\WinAgent;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class DemoController extends Controller
{
    public function insertAction()
    {
        $em = $this->getDoctrine()->getManager();
        try {
            for ($i=1; $i<=50; $i++) {
                $intro = new Intro();
                $intro->setTitle("Title".$i);
                $intro->setContent("Content".$i);
                $intro->setAddtime(time());
                $intro->setAuthor("tang".$i);
                $intro->setCategory("Category".$i);
                $em->persist($intro);
                $em->flush();
            }
        } catch (Exception $e) {
            return new Response($e->getMessage());
        }
        return new Response("insert success");
    }

    /**
     * @return Response
     */
    public function jqgirdAction()
    {
        return $this->render("IcsocUIBundle:Default:jqgird.html.twig");
    }

    /**
     * @param Request $request
     * @return Response
     */
    public function jlistAction(Request $request)
    {
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'asc');
        $sidx = $request->get('sidx', 'id');
        $fliter = $request->get('fliter', '');
        $em = $this->getDoctrine()->getManager();
        $where = '';
        $parameter  = array();
        if (!empty($fliter)) {
            $json = json_decode($fliter, true);
            if (isset($json['agentNumber']) && !empty($json['agentNumber'])) {
                $where ='AND intro.title = :title ';
                $parameter['title'] = $json['agentNumber'];
            }
        }
        $query = $em->createQuery(
            "SELECT count(intro) ".
            "FROM IcsocUIBundle:Intro intro ".
            "WHERE 1=1 ".$where
        )->setParameters($parameter);
        try {
            $single = $query->getSingleResult();
            $count = $single['1'];
        } catch (NoResultException $e) {
            $count = 0;
        }
        if ($count > 0) {
            $totalPage = ceil($count/$rows);
        } else {
            $totalPage = 1;
        }
        if ($page > $totalPage) {
            $page = $totalPage;
        }
        $start = ($page -1 )*$rows;
        $query = $em->createQuery(
            "SELECT intro
            FROM IcsocUIBundle:Intro intro
            WHERE 1=1 {$where}
            ORDER BY intro.".$sidx.' '.$sord
        )->setParameters($parameter);
        $query->setFirstResult($start);
        $query->setMaxResults($rows);
        $all = $query->getResult();
        $reponse['rows'] = $all;
        $reponse['page'] = $page;
        $reponse['total'] = $totalPage;
        $reponse['records'] = $count;
        $serializer = $this->get('serializer');
        $response = $serializer->serialize($reponse, 'json');

        return new Response($response);
//        $em = $this->getDoctrine()->getManager();
//        $query = $em->createQuery(
//            "SELECT "
//        );
    }

    public function operAction(Request $request)
    {
        $oper = $request->get('oper');
        $id = $request->get('id');
        $em = $this->getDoctrine()->getManager();
        if ($oper == 'del') {
            $intro = $em->getRepository('IcsocUIBundle:WinAgent')->find($id);
            $em->remove($intro);
            $em->flush();
            return new JsonResponse(array('message'=>'删除成功'));
        } else {

        }
        return new JsonResponse(array('message'=>'删除失败'));
    }

    //表单；
    public function formAction(Request $request)
    {
        $intro = new Intro();
        $form = $this->createForm('intro', $intro);
        $form->handleRequest($request);
        if ($form->isValid()) {

        }
        return $this->render('IcsocUIBundle:Default:form.html.twig', array(
            'form'=>$form->createView()
        ));
    }

    //wysiwyg && markdown 编辑器
    public function editerAction()
    {
        return $this->render('IcsocUIBundle:Default:editer.html.twig');
    }

    //colorbox
    public function colorboxAction()
    {
        return $this->render('IcsocUIBundle:Default:colorbox.html.twig');
    }

    /**
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     * 创建用户
     */
    public function winAgentAction(Request $request)
    {
        $agent = new WinAgent();
        $form = $this->createForm('winagent', $agent);
        if ($request->isMethod('POST')) {
            $form = $form->handleRequest($request);
            if ($form->isValid()) {
                $que = $agent->getUserQueues();
                $agent->setUserQueues(implode(',', $que));
                $em = $this->getDoctrine()->getManager();
                $em->persist($agent);
                $em->flush();
//              flash提示信息
//                $this->get('session')->getFlashBag()->add(
//                    'success', //success是成功,danger是错误；
//                    '添加坐席成功'
//                );
//                return $this->redirect($this->generateUrl('icsoc_ui_agent'));
                $data = array(
                    'data'=>array(
                        'msg_detail'=>'添加坐席成功',
                        'link' => array(
                            array('text'=>'继续添加','href'=>$this->generateUrl('icsoc_ui_agent')),
                            array('text'=>'坐席列表','href'=>$this->generateUrl('icsoc_ui_list_agent')),
                        )
                    )
                );
                return $this->redirect($this->generateUrl('icsoc_ui_message', $data));

            }
        }
        return $this->render(
            'IcsocUIBundle:Default:crete_agent.html.twig',
            array(
                'form'=>$form->createView()
            )
        );
    }

    /**
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function editAgentAction(Request $request)
    {
        $id = $request->get('id', '');
        $agent = $this->getDoctrine()->getRepository('IcsocUIBundle:WinAgent')->find($id);
        $agent->setUserQueues(explode(',', $agent->getUserQueues()));
        $form = $this->createForm('winagent', $agent);
        if ($request->isMethod('POST')) {
            $form = $form->handleRequest($request);
            if ($form->isValid()) {
                $que = $agent->getUserQueues();
                $agent->setUserQueues(implode(',', $que));
                $em = $this->getDoctrine()->getManager();
                $em->flush();
                return $this->redirect($this->generateUrl('icsoc_ui_agent'));
            }
        }
        return $this->render(
            'IcsocUIBundle:Default:crete_agent.html.twig',
            array(
                'form'=>$form->createView()
            )
        );
    }

    public function listAgentAction(Request $request)
    {
        if ($request->get('flag')) {
            $page = $request->get('page', 1);
            $rows = $request->get('rows', 10);
            $sord = $request->get('sord', 'asc');
            $sidx = $request->get('sidx');
            $sidx = empty($sidx) ? 'id' : $sidx;
            $fliter = $request->get('fliter', '');
            $em = $this->getDoctrine()->getManager();
            $where = '';
            $parameter  = array();
            if (!empty($fliter)) {
                $json = json_decode($fliter, true);
                if (isset($json['agentNumber']) && !empty($json['agentNumber'])) {
                    $where ='AND w.agentNumber = :agentNumber ';
                    $parameter['agentNumber'] = $json['agentNumber'];
                }
            }
            $query = $em->createQuery(
                "SELECT count(winAgent) ".
                "FROM IcsocUIBundle:WinAgent winAgent ".
                "WHERE 1=1 ".$where
            )->setParameters($parameter);
            try {
                $single = $query->getSingleResult();
                $count = $single['1'];
            } catch (NoResultException $e) {
                $count = 0;
            }
            if ($count > 0) {
                $totalPage = ceil($count/$rows);
            } else {
                $totalPage = 1;
            }
            if ($page > $totalPage) {
                $page = $totalPage;
            }
            $start = ($page -1 )*$rows;
            $query = $em->createQuery(
                'SELECT w,roleName '.
                'FROM IcsocUIBundle:WinAgent w  '.
                'LEFT JOIN w.agRoleName roleName '.
                'WHERE 1=1 '.$where.
                'ORDER BY w.'.$sidx.' '.$sord
            )->setParameters($parameter);
            $query->setFirstResult($start);
            $query->setMaxResults($rows);
            $all = $query->getResult();
            $reponse['rows'] = $all;
            $reponse['page'] = $page;
            $reponse['total'] = $totalPage;
            $reponse['records'] = $count;
            $serializer = $this->get('serializer');
            $response = $serializer->serialize($reponse, 'json');

            return new Response($response);
        }
        $this->get('icsoc_bread')->add("坐席管理")->add("坐席列表");

        return $this->render("IcsocUIBundle:Agent:agentList.html.twig");
    }

    /**
     * @return Response
     */
    public function testValidatorAction()
    {
        $agent = new WinAgent();
        $validator = $this->get('validator');
        $errors = $validator->validate($agent);
        if (count($errors) > 0) {
            $error_message = (string) $errors;
            return new Response($error_message);
        }
        return new Response('success');
    }

    /**
     * chosen插件案例
     */
    public function chosenAction()
    {
        return $this->render('IcsocUIBundle:Default:chosen.html.twig');
    }

    /**
     *  taginput插件案例
     */
    public function tagInputAction()
    {
        return $this->render('IcsocUIBundle:Default:taginput.html.twig');
    }

    /**
     * maskinput插件案例
     */
    public function maskinputAction()
    {
        return $this->render('IcsocUIBundle:Default:maskinput.html.twig');
    }

    /**
     * inputlimiter插件案例
     */
    public function limiterAction()
    {
        return $this->render('IcsocUIBundle:Default:limiter.html.twig');
    }

    /**
     * spinner案例
     */
    public function spinnerAction()
    {
        return $this->render('IcsocUIBundle:Default:spinner.html.twig');
    }

    /**
     * wizard案例
     */
    public function wizardAction()
    {
        return $this->render('IcsocUIBundle:Default:wizard.html.twig');
    }

    /**
     * tree案例
     */
    public function treeAction()
    {
        return $this->render('IcsocUIBundle:Default:tree.html.twig');
    }

    /**
     * validate案例
     */
    public function validateAction()
    {
        return $this->render('IcsocUIBundle:Default:validate.html.twig');
    }

    /**
     * dropzone案例(文件上传)
     */
    public function dropzoneAction()
    {
        return $this->render('IcsocUIBundle:Default:dropzone.html.twig');
    }

    /**
     * colorpicker案例(文件上传)
     */
    public function colorpickerAction()
    {
        return $this->render('IcsocUIBundle:Default:colorpicker.html.twig');
    }

    /**
     * bootbox案例(弹框)
     */
    public function bootboxAction()
    {
        return $this->render('IcsocUIBundle:Default:bootbox.html.twig');
    }

    /**
     * gritter案例(消息提醒)
     */
    public function gritterAction()
    {
        return $this->render('IcsocUIBundle:Default:gritter.html.twig');
    }

    /**
     * nestable案例(可移动列表)
     */
    public function nestableAction()
    {
        return $this->render('IcsocUIBundle:Default:nestable.html.twig');
    }

    /**
     * slimscroll案例(内容滚动)
     */
    public function slimscrollAction()
    {
        return $this->render('IcsocUIBundle:Default:slimscroll.html.twig');
    }

    /**
     * @param Request $request
     * @return Response
     * 信息跳转；
     */
    public function messageAction(Request $request)
    {
        $data = $request->get('data');
        if (!isset($data['link']) || count($data['link'])==0) {
            $data['link'] = array(
                array('text'=>'返回', 'href'=>'javascript:history.go(-1)')
            );
        }
        if (!isset($data['type'])) {
            $data['type'] = 'info';
        }
        $data['default_url'] = $data['link'][0]['href'];
        $data['link_type'] = isset($data['link'][0]['type']) ? 1 : '';
        $data['auto_redirect'] = isset($data['auto_redirect']) ? $data['auto_redirect'] : true;

        return $this->render(
            'IcsocUIBundle:Default:message.html.twig',
            array(
                'datavalue'=>$data
            )
        );
    }

    public function testFormAction()
    {

    }
}
